<?php

namespace app\cdc\validate\admin;

use app\common\model\mysql\GoodsModel;
use app\common\model\mysql\GoodsSpecModel;
use app\common\model\mysql\TeamGoodsModel;
use app\common\model\mysql\TeamGoodsSpecModel;

class TeamGoodsValidate extends \app\common\validate\BaseValidate
{
    protected $rule = [
        'name' => 'require|checkName',
        'category_id' => 'require',
        'sub_category_id' => 'require|array',
        'price' => 'require',
        'price_ratio' => 'require',
        'price_init_market' => 'require',
        'define' => 'require',
        'status' => 'checkStatus',
        'profit_num' => 'require',
    ];

    protected $message = [
        'name.require' => '商品名称 必填',
        'category_id.require' => '商品分类 必选',
        'sub_category_id.require' => '商品子分类 必选',
        'sub_category_id.array' => '商品子分类是数组',
        'price.require' => '成本价 必填',
        'price_init_market.require' => '市场价 必选',
        'price_ratio.require' => '系数 必选',
        'profit_num.require' => '分润值 必填',
    ];

    protected $scene = [
        'update' => ['name', 'category_id', 'sub_category_id', 'price', 'price_ratio', 'define', 'price_init_market', 'profit_num'],
        'renew' => ['status'],
    ];

    protected function checkName($value, $rule, $data = [])
    {
        $where[] = ['name', '=', $data['name']];
        !empty($data['id']) ? $where[] = ['id', '<>', $data['id']] : false;
        if (TeamGoodsModel::checkRowExists($where)) {
            return '商品名称已存在';
        }
        return true;
    }

    protected function checkStatus($value, $rule, $data = [])
    {
        if (!TeamGoodsSpecModel::checkRowExists(['goods_id' => $data['id'], 'status' => 1])) {
            return '商品没有规格，无法上架';
        }
        return true;
    }

}